import { LoginApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

/* const getDefaultState = () => {
  return {
    token: getToken()

  }
} */

const state = {
  token: getToken() || ''
}

const mutations = {
  /* RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  }, */
  SET_TOKEN: (state, token) => {
    state.token = token
    // 将token存入到 cookie
    setToken(token)
  },
  // 清空token
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    try {
      const res = await LoginApi(userInfo)
      console.log(res)
      commit('SET_TOKEN', res.data.token)
      // return res // 这里是一个 promise
      if (res.data.success) {
        return Promise.resolve(res.data)
      } else {
        return Promise.reject(res.data.msg)
      }
    } catch (error) {
      return Promise.reject(error)
    }
    // const res = await LoginApi(userInfo)
    // console.log(res)
    // commit('SET_TOKEN', res.data.token)
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // 清空
  resetToken({ commit }) {
    commit('REMOVE_TOKEN')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

